package com.cjm.algorithm.queue;

import java.util.*;

public class NestedIterator341 implements Iterator<Integer> {
    Deque<Integer> stack = new ArrayDeque<>();

    public NestedIterator341(List<NestedInteger> nestedList) {
        for (NestedInteger nestedInteger : nestedList) {
            if (nestedInteger.isInteger()) {
                stack.addLast(nestedInteger.getInteger());
            } else {
                stack.addAll(parse(nestedInteger));
            }
        }
    }

    public Deque<Integer> parse(NestedInteger item) {
        Deque<Integer> xx = new ArrayDeque<>();
        if (item.isInteger()) {
            xx.addLast(item.getInteger());
            return xx;
        }
        List<NestedInteger> list = item.getList();
        for (NestedInteger nestedInteger : list) {
            if (nestedInteger.isInteger()) {
                xx.addLast(nestedInteger.getInteger());
            } else {
                xx.addAll(parse(nestedInteger));
            }
        }
        return xx;
    }

    @Override
    public Integer next() {
        return stack.pollFirst();
    }

    @Override
    public boolean hasNext() {
        return !stack.isEmpty();
    }
}